package com.qishanor.framework.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qishanor.framework.constant.CommonConstant;
import com.qishanor.framework.mybatis.support.DsJdbcUrlEnum;
import com.qishanor.framework.constant.enums.StyleTypeEnum;
import com.qishanor.system.mapper.GenDatasourceMapper;
import com.qishanor.system.mapper.GeneratorMapper;
import com.qishanor.system.model.*;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.springframework.context.ApplicationContext;
import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器 工具类
 */

@Slf4j
@UtilityClass
public class GenUtil {

	private final String MENU_SQL_VM = "menu.sql.vm";

	private final String ENTITY_JAVA_VM = "Entity.java.vm";

	private final String MAPPER_JAVA_VM = "Mapper.java.vm";

	private final String MAPPER_XML_VM = "Mapper.xml.vm";

	private final String SERVICE_JAVA_VM = "Service.java.vm";

	private final String SERVICE_IMPL_JAVA_VM = "ServiceImpl.java.vm";

	private final String CONTROLLER_JAVA_VM = "Controller.java.vm";

	public final String CRUD_PREFIX = "export const tableOption =";

	private final String AVUE_API_JS_VM = "avue/api.js.vm";

	private final String AVUE_CRUD_JS_VM = "avue/crud.js.vm";

	private final String AVUE_INDEX_VUE_VM = "avue/index.vue.vm";

	private final String ELE_INDEX_VUE_VM = "element/index.vue.vm";

	private final String ELE_ADD_UPDATE_VUE_VM = "element/form.vue.vm";



	/**
	 * 根据目标数据源名称动态匹配Mapper
	 *
	 * @param dsName
	 * @return
	 */
	public GeneratorMapper getMapper(String dsName) {
		// 获取目标数据源数据库类型
		GenDatasourceMapper datasourceMapper = SpringContextHolder.getBean(GenDatasourceMapper.class);
		GenDatasource datasourceConf = datasourceMapper
				.selectOne(Wrappers.<GenDatasource>lambdaQuery().eq(GenDatasource::getName, dsName));

		String dbConfType;
		// 默认MYSQL 数据源
		if (datasourceConf == null) {
			dbConfType = DsJdbcUrlEnum.MYSQL.getDbName();
		} else {
			dbConfType = datasourceConf.getDbType();
		}

		// 获取全部数据实现
		ApplicationContext context = SpringContextHolder.getApplicationContext();
		Map<String, GeneratorMapper> beansOfType = context.getBeansOfType(GeneratorMapper.class);

		// 根据数据类型选择mapper
		for (String key : beansOfType.keySet()) {
			if (StrUtil.containsIgnoreCase(key, dbConfType)) {
				return beansOfType.get(key);
			}
		}

		throw new IllegalArgumentException("dsName 不合法: " + dsName);
	}


	/**
	 * 生成代码
	 *
	 * @return
	 */
	@SneakyThrows
	public Map<String, String> generatorCode(GenConfig genConfig, Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zip) {
		// 配置信息
		Configuration config = getConfig();
		boolean hasBigDecimal = false;
		// 表信息
		GenTableEntity genTableEntity = new GenTableEntity();
		genTableEntity.setDbType(table.get("dbType"));
		genTableEntity.setTableName(table.get("tableName"));

		String tableComments= StrUtil.blankToDefault(genConfig.getComments(),table.get("tableComment"));
		genTableEntity.setComments(tableComments);
		String tablePrefix=StrUtil.blankToDefault(genConfig.getTablePrefix(),config.getString("tablePrefix"));

		// 表名转换成Java类名
		String className = tableToJava(genTableEntity.getTableName(), tablePrefix);
		genTableEntity.setCaseClassName(className);
		genTableEntity.setLowerClassName(StringUtils.uncapitalize(className));

		// 列信息
		List<GenColumnEntity> columnList = new ArrayList<>();
		for (Map<String, String> column : columns) {
			GenColumnEntity genColumnEntity = new GenColumnEntity();
			genColumnEntity.setColumnName(column.get("columnName"));
			genColumnEntity.setColumnType(column.get("columnType"));
			genColumnEntity.setDataType(column.get("dataType"));
			genColumnEntity.setExtra(column.get("extra"));
			genColumnEntity.setNullable("NO".equals(column.get("isNullable")));

			// 列名转换成Java属性名
			String attrName = columnToJava(genColumnEntity.getColumnName());
			genColumnEntity.setCaseAttrName(attrName);
			genColumnEntity.setLowerAttrName(StringUtils.uncapitalize(attrName));
			// 判断注释是否为空
			String columnComments= ObjectUtil.defaultIfEmpty(column.get("comments"),()->StrUtil.removeAllLineBreaks(column.get("comments")),genColumnEntity.getLowerAttrName());
			genColumnEntity.setComments(columnComments);

			// 列的数据类型，转换成Java类型
			String dataType = StrUtil.subBefore(genColumnEntity.getDataType(), "(", false);
			String attrType = config.getString(dataType, "unknowType");
			genColumnEntity.setAttrType(attrType);
			if (!hasBigDecimal && "BigDecimal".equals(attrType)) {
				hasBigDecimal = true;
			}
			// 是否主键
			if ("PRI".equalsIgnoreCase(column.get("columnKey")) && genTableEntity.getPk() == null) {
				genTableEntity.setPk(genColumnEntity);
			}

			columnList.add(genColumnEntity);
		}
		genTableEntity.setColumns(columnList);

		// 没主键，则第一个字段为主键
		if (genTableEntity.getPk() == null) {
			genTableEntity.setPk(genTableEntity.getColumns().get(0));
		}

		// 封装模板数据
		Map<String, Object> map = new HashMap<>(16);
		map.put("dbType", genTableEntity.getDbType());
		map.put("tableName", genTableEntity.getTableName());
		map.put("pk", genTableEntity.getPk());
		map.put("className", genTableEntity.getCaseClassName());
		map.put("classname", genTableEntity.getLowerClassName());
		map.put("pathName", genTableEntity.getLowerClassName().toLowerCase());
		map.put("columns", genTableEntity.getColumns());
		map.put("hasBigDecimal", hasBigDecimal);
		map.put("datetime", DateUtil.now());
		map.put("comments", ObjectUtil.defaultIfBlank(genConfig.getComments(),genTableEntity.getComments()));
		map.put("author",ObjectUtil.defaultIfBlank(genConfig.getAuthor(),config.getString("author")));
		map.put("moduleName",ObjectUtil.defaultIfBlank(genConfig.getModuleName(),config.getString("moduleName")));
		map.put("package", ObjectUtil.defaultIfBlank(genConfig.getPackageName(),config.getString("package")));
		map.put("mainPath", ObjectUtil.defaultIfBlank(genConfig.getPackageName(),config.getString("mainPath")));

		// 渲染数据
		return renderData(genConfig, zip, genTableEntity, map);
	}


	/**
	 * 渲染数据
	 *
	 * @param genConfig   配置信息
	 * @param zip         流 （为空，直接返回Map）
	 * @param tableEntity 表基本信息
	 * @param map         模板参数
	 * @return map key-filename value-contents
	 * @throws IOException
	 */
	private Map<String, String> renderData(GenConfig genConfig, ZipOutputStream zip, GenTableEntity tableEntity, Map<String, Object> map) throws IOException {
		// 设置velocity资源加载器
		Properties prop = new Properties();
		prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		Velocity.init(prop);
		VelocityContext context = new VelocityContext(map);

		// 获取模板列表
		List<String> templates = getTemplates(genConfig);
		Map<String, String> resultMap = new HashMap<>(8);

		for (String template : templates) {

			// 渲染模板
			StringWriter sw = new StringWriter();
			Template tpl = Velocity.getTemplate(template, CharsetUtil.UTF_8);
			tpl.merge(context, sw);

			// 添加到zip
			String fileName = getFileName(template, tableEntity.getCaseClassName(), map.get("package").toString(), map.get("moduleName").toString());
			if (zip != null) {
				zip.putNextEntry(new ZipEntry(Objects.requireNonNull(fileName)));
				IoUtil.write(zip, StandardCharsets.UTF_8, false, sw.toString());
				IoUtil.close(sw);
				zip.closeEntry();
			}
			resultMap.put(template, sw.toString());
		}

		return resultMap;
	}

	/**
	 * 获取配置信息
	 */
	public Configuration getConfig() {
		try {
			return new PropertiesConfiguration("generator.properties");
		} catch (ConfigurationException e) {
			throw new RuntimeException("获取配置文件失败，", e);
		}
	}


	/**
	 * 表名转换成Java类名
	 */
	private String tableToJava(String tableName, String tablePrefix) {
		if (StringUtils.isNotBlank(tablePrefix)) {
			tableName = tableName.replaceFirst(tablePrefix, "");
		}
		return columnToJava(tableName);
	}

	/**
	 * 列名转换成Java属性名
	 */
	public String columnToJava(String columnName) {
		return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
	}

	/**
	 * 配置
	 *
	 * @param config
	 * @return
	 */
	private List<String> getTemplates(GenConfig config) {
		List<String> templates = new ArrayList<>();
		templates.add("template/Entity.java.vm");
		templates.add("template/Mapper.java.vm");
		templates.add("template/Mapper.xml.vm");
		templates.add("template/Service.java.vm");
		templates.add("template/ServiceImpl.java.vm");
		templates.add("template/Controller.java.vm");
		templates.add("template/menu.sql.vm");
		templates.add("template/avue/api.js.vm");

		if (StyleTypeEnum.AVUE.getStyle().equals(config.getStyle())) {
			templates.add("template/avue/index.vue.vm");
			templates.add("template/avue/crud.js.vm");
		} else {
			templates.add("template/element/index.vue.vm");
			templates.add("template/element/form.vue.vm");
		}

		return templates;
	}


	/**
	 * 获取文件名
	 */
	private String getFileName(String template, String className, String packageName, String moduleName) {
		String packagePath = CommonConstant.BACK_END_PROJECT + File.separator + "src" + File.separator + "main"
				+ File.separator + "java" + File.separator;

		if (StringUtils.isNotBlank(packageName)) {
			packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
		}

		if (template.contains(ENTITY_JAVA_VM)) {
			return packagePath + "model" + File.separator + className + ".java";
		}

		if (template.contains(MAPPER_JAVA_VM)) {
			return packagePath + "mapper" + File.separator + className + "Mapper.java";
		}

		if (template.contains(MAPPER_XML_VM)) {
			return packagePath + "mapper" + File.separator +"xml"+File.separator+ className + "Mapper.xml";
		}

		if (template.contains(SERVICE_JAVA_VM)) {
			return packagePath + "service" + File.separator + className + "Service.java";
		}

		if (template.contains(SERVICE_IMPL_JAVA_VM)) {
			return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
		}

		if (template.contains(CONTROLLER_JAVA_VM)) {
			return packagePath + "controller" + File.separator + className + "Controller.java";
		}

		if (template.contains(MENU_SQL_VM)) {
			return className.toLowerCase() + "_menu.sql";
		}

		if (template.contains(AVUE_INDEX_VUE_VM) || template.contains(ELE_INDEX_VUE_VM)) {
			return CommonConstant.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
					+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
					+ "index.vue";
		}

		if (template.contains(AVUE_API_JS_VM)) {
			return CommonConstant.FRONT_END_PROJECT + File.separator + "src" + File.separator + "api" + File.separator
					+ className.toLowerCase() + ".js";
		}

		if (template.contains(AVUE_CRUD_JS_VM)) {
			return CommonConstant.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
					+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
					+ className.toLowerCase() + ".js";

		}

		if (template.contains(ELE_ADD_UPDATE_VUE_VM)) {
			return CommonConstant.FRONT_END_PROJECT + File.separator + "src" + File.separator + "views"
					+ File.separator + moduleName + File.separator + className.toLowerCase() + File.separator
					+ className.toLowerCase() + "-form.vue";
		}
		return null;
	}


}
